import 'package:family_expense/features/income_expense/constants/payment_type.dart';
import 'package:family_expense/features/income_expense/widgets/income_expense_detail_shared.dart';
import 'package:family_expense/features/income_expense_analysis/models/income_expense_annual_summry.dart';
import 'package:family_expense/features/income_expense_analysis/services/income_expense_analysis_service.dart';
import 'package:family_expense/features/income_expense_analysis/widgets/income_expense_annual_analysis.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class IncomeExpenseAnalysisHome extends StatefulWidget {
  const IncomeExpenseAnalysisHome({super.key});

  @override
  State<IncomeExpenseAnalysisHome> createState() =>
      _IncomeExpenseAnalysisHomeState();
}

class _IncomeExpenseAnalysisHomeState extends State<IncomeExpenseAnalysisHome> {
  final IncomeExpenseAnalysisService _incomeExpenseAnalysisService =
      IncomeExpenseAnalysisService();

  List<IncomeExpenseAnnualSummary>? _yearSummaries;

  @override
  void initState() {
    super.initState();

    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return _yearSummaries != null
        ? RefreshIndicator(
            onRefresh: _loadData,
            child: ListView.builder(
              itemCount: _yearSummaries!.length,
              itemBuilder: (context, index) => _buildSummaryCard(index),
            ),
          )
        : const MyPageTopCenterLoadingIndicator();
  }

  /// Builds the card for the summary based on each index.
  Widget _buildSummaryCard(int index) {
    const numberTextStyle = TextStyle(fontSize: 14.0);
    const iconSize = 15.0;

    final balanceNumberTextStyle = numberTextStyle.copyWith(
      fontWeight: FontWeight.bold,
    );

    const divider = SizedBox(height: 10.0);

    return GestureDetector(
      child: Card(
        elevation: 6.0,
        margin: const EdgeInsets.only(
          left: 10.0,
          top: 10.0,
          right: 10.0,
          bottom: 5.0,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              padding: const EdgeInsets.only(
                left: 10.0,
                top: 10.0,
                right: 10.0,
                bottom: 5.0,
              ),
              child: Text(
                _yearSummaries![index].year.toString(),
                style: const TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.w800,
                ),
              ),
            ),
            const Divider(thickness: 1.0),
            Container(
              padding: const EdgeInsets.all(10.0),
              child: Row(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      IncomeExpenseDetailShared.getTypeIcon(
                        PaymentType.cash,
                        size: iconSize,
                      )!,
                      divider,
                      IncomeExpenseDetailShared.getTypeIcon(
                        PaymentType.creditCard,
                        size: iconSize,
                      )!,
                      divider,
                      Icon(MdiIcons.bellOutline, size: iconSize),
                    ],
                  ),
                  const SizedBox(width: 10.0),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${formatNumber(_yearSummaries![index].cashIncome)} - ${formatNumber(_yearSummaries![index].cashExpense!.abs())}',
                          style: numberTextStyle,
                        ),
                        divider,
                        Text(
                          '${formatNumber(_yearSummaries![index].creditCardIncome)} - ${formatNumber(_yearSummaries![index].creditCardExpense!.abs())}',
                          style: numberTextStyle,
                        ),
                        divider,
                        Text(
                          '${formatNumber(_yearSummaries![index].cashIncome! + _yearSummaries![index].creditCardIncome!)} - ${formatNumber(_yearSummaries![index].cashExpense!.abs() + _yearSummaries![index].creditCardExpense!.abs())}',
                          style: numberTextStyle,
                        ),
                      ],
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        formatBalanceNumber(_yearSummaries![index].cashBalance),
                        style: balanceNumberTextStyle.copyWith(
                          color: IncomeExpenseDetailShared.getAmountColor(
                            _yearSummaries![index].cashBalance,
                          ),
                        ),
                      ),
                      divider,
                      Text(
                        formatBalanceNumber(
                          _yearSummaries![index].creditCardBalance,
                        ),
                        style: balanceNumberTextStyle.copyWith(
                          color: IncomeExpenseDetailShared.getAmountColor(
                            _yearSummaries![index].creditCardBalance,
                          ),
                        ),
                      ),
                      divider,
                      Text(
                        formatBalanceNumber(
                          _yearSummaries![index].cashBalance! +
                              _yearSummaries![index].creditCardBalance!,
                        ),
                        style: balanceNumberTextStyle.copyWith(
                          color: IncomeExpenseDetailShared.getAmountColor(
                            _yearSummaries![index].cashBalance! +
                                _yearSummaries![index].creditCardBalance!,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(width: 20.0),
                ],
              ),
            ),
            const SizedBox(height: 5.0),
          ],
        ),
      ),
      onTap: () async {
        // Overall summary contains string like '2020-2023'.
        // We can determine if this item is annual summary or overall summary.
        final year = int.tryParse(_yearSummaries![index].year!);

        bool? dataUpdated;

        if (year == null) {
          dataUpdated = await NavigatorHelper.push<bool>(
            context,
            IncomeExpenseAnnualAnalysis(
              yearRange: _yearSummaries![index].year!,
            ),
          );
        } else {
          dataUpdated = await NavigatorHelper.push<bool>(
            context,
            IncomeExpenseAnnualAnalysis(year: year),
          );
        }

        // If data updated we need to reload the summary data.
        if (dataUpdated == true) {
          _loadData();
        }
      },
    );
  }

  /// Loads annual summary data.
  Future<void> _loadData() async {
    final result = await _incomeExpenseAnalysisService
        .querySummaryByExistingYears();

    if (mounted) {
      setState(() => _yearSummaries = result);
    }
  }
}
